import React from 'react'
import {
    Button,
    message,
    Modal
} from 'antd'
import SearchBar from "../../components/SearchBar";
import Table from '../../components/Table'
import {
    FormModal
} from '../../components/ModalForm2'
import 'whatwg-fetch'
import API from '../../axios/api'
import { UserType} from '../../utils/system-data'
import {withRouter} from "react-router-dom";
import {inject, observer} from "mobx-react";
import SalesDetailList from "./DetailList";

require('es6-promise').polyfill();
const confirm = Modal.confirm


const columns = [
    { dataIndex: '', title: '序号', width: 80, render: (text, record,index) =>  <span>{index + 1}</span>},
    { dataIndex: 'HallName', title: '班级', width: 200,},
    { dataIndex: 'HallUserCount', title: '班级经营者数量', width: 240,},
    { dataIndex: 'HallUserNames', title: '班主任', width: 200, },

]
@withRouter @inject('appStore') @observer
class InsideUser extends React.Component {
    constructor(props) {
        super(props)
        let {user, rudder, rudderList} = props.appStore
        this.state = {
            user: user,
            rudder: rudder,
            rudderList: rudderList,
            tData: [],
            item: {},
            loading: true,
            modalShow: false,
            modalShowEdit: false,
            searchHallId: "-1",
            initUserList: [],
            initHallList: [],
            modalShowDetail:false,
            Page: 1,
            Pages:1,
            RudderId:user.RudderId,
            HallId:'',
            HallName:''
        }
        this._initRoleList = []
        this._initUserList = []
    }

    componentWillReceiveProps(nextProps){
        let {user, rudder, rudderList} = this.props.appStore

         this.setState({
             user: user,
             rudder: rudder,
             rudderList: rudderList,
             RudderId:user.RudderId
         })
     }

    onPageChange = (e) =>{
        this.setState({
            Page:e,
        },()=>{
            this.fetchTableData()
        })
    }

    // 获取表格数据
    fetchTableData = (searchFields) => {
        let parms = {
            Page:this.state.Page,
            PageSize: 10,
            RudderId: searchFields && searchFields.RudderId ? searchFields.RudderId : this.state.RudderId,
            RankType: -1,
            HallName: searchFields && searchFields.HallName ? searchFields.HallName : this.state.HallName,
        }
        API.fetchHallSallPages(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List,
                    Pages:res.Data.Pages
                });
            }
            this.setState({
                loading: false
            });
        })
    }

    initHallList =  async (rudderId) => {
        let params = {
            ...API.config,
            RudderId:  rudderId || this.state.rudder.value,
        }
        await API.fetchHallPages(params).then((res) => {
            let initHallList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => initHallList.push({value: item.Id, mean: item.HallName}))
                this.setState({
                    initHallList
                })
            }
        })
    }
    
    initUserList =  async (rudderId) => {
        let params = {
            ...API.config,
            RudderId:rudderId || this.state.RudderId,
            RankType: -1,
        }
        await API.fetchUserPages(params).then((res) => {
            let _initUserList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initUserList.push({value: item.UserId, mean: item.NickName}))
                this.setState({
                    initUserList: _initUserList
                })
            }
        })
    }
    initRoleList =  async () => {
        let params = {}
        await API.fetchRoles(params).then((res) => {
            if(res.Code === 200) {
                res.Data && res.Data.map(item => this._initRoleList.push({key: item.Id, value: item.RoleName}))
            }
        })
    }

    

    componentDidMount() {
        this.fetchTableData()
    }

    componentWillMount() {
        this.initHallList()
        this.initRoleList()
        this.initUserList()
    }
    add = () =>{
        this.setState({
            modalShow: true
        })
    }

    onOk = (param) =>{
       param.RankType = UserType.HALL
        API.editInternalUser(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
                this.fetchTableData()
            }
            else message.error(res.Message)
        })
    }

    onCancel = () =>{
        this.setState({
            modalShow:false,
            modalShowDetail:false
        })
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'detail') {
            this.setState({
                modalShowDetail:true,
                item:item
            })
        } 
    }

    handerDel(item, status){
        return API.delRole({Id: item.Id, Status: status})
    }

    rudderChange(v){
        console.log(123123123)
        console.log(v)
        
        this.setState({
            RudderId:v
        })

        this.initHallList(v)
        this.initUserList(v)
    }

    searchRudderChange = (v) =>{
        this.setState({
            searchHallId : "-1"
        })
        this.initHallList(v)
    }

    onSearchChange = async (value) => {
    //   let params = {
    //     ...API.config,
    //     RudderId: this.state.RudderId,
    //     NickName: value
    //   }
    //   await API.fetchUserPages(params).then((res) => {
    //     let _initUserList = []
    //     if(res.Code === 200) {
    //         res.Data.List && res.Data.List.map(item => _initUserList.push({value: item.UserId, mean: item.NickName}))
    //         this.setState({
    //             initUserList:_initUserList
    //         })
    //     }
    //   })
    }

    fields = () => {
        let fields = [
            { label: '用户', type: 'select2', name: 'UserId',
                showSearch: true,
                items: () =>  this.state.initUserList,
                onSearch:(value) => this.onSearchChange(value),
                options: {
                    rules: [
                        { required: true, message: '用户必填!',}
                    ]
                }
            },
            {
                label: '班级',
                type: 'select',
                name: 'HallId',
                items: () => this.state.initHallList,
                options: {
                    rules: [{
                        required: true,
                        message: '权限类型必输!',
                    }]
                }
            },
            { label: '真实姓名', type: 'input', name: 'RealName',
                options: {
                    rules: [
                        { required: true, message: '真实姓名必填!',}
                    ]
                }
            },
            { label: '微信号', type: 'input', name: 'WXQRCode',
                options: {
                    rules: [
                        { required: true, message: '微信号必填!',}
                    ]
                }
            },
            { label: '手机号', type: 'input', name: 'CellPhone',
                options: {
                    rules: [
                        { required: true, message: '手机号必填!',}
                    ]
                }
            },
        ]
        if(this.state.user.UserRankType === UserType.ADMIN || this.state.user.RudderId == "-") {
            fields = [{
                label: '分舵',
                type: 'select',
                name: 'RudderId',
                items: () => this.state.rudderList,
                onChange:(value) => this.rudderChange(value),
                RudderId:this.state.RudderId,
                options: {
                    rules: [{
                        required: true,
                        message: '必选!',
                    }]
                }
            },].concat(fields)
        }
        return fields
    }

    onSearch = (searchFields) => {

        if(searchFields.RudderId){
            this.setState({
                RudderId:searchFields.RudderId
            })
        }
        if(searchFields.HallName){
            this.setState({
                HallName:searchFields.HallName
            })
        }
        this.setState({
            HallName:searchFields.HallName,
            Page:1
        },()=>{
            this.fetchTableData(searchFields)
        })
       
    }

    searchFields = () => {
        let fields = [{
            title: '班级名称',
            key: 'HallName',
            type: 'input',
        }, ]
        if(this.state.user.UserRankType === UserType.ADMIN || this.state.user.RudderId == "-"){
            fields = [ ].concat(fields)
        }
        return fields
    }

    render() {
        return (
            <div id="wrap">
              
                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns }
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [
                                { key: 'detail', name: '详情', color: 'blue', icon: 'ordered-list'},
                            ]}
                            scroll={{y: 1000 }}
                            total={this.state.Pages}
                            onChange={this.onPageChange}
                            currentPage={this.state.Page}
                        />
                    </div>
                </div>
                <FormModal
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加班主任"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                />

                <SalesDetailList
                    modalKey="add"
                    visible={this.state.modalShowDetail}
                    title="详情"
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    Id={this.state.item.Id}
                    RudderId={this.state.item.RudderId}
                    width="70%"
                />
            </div>
        )
    }
}
export default InsideUser
